package com.wangbo.basic;

/**
 * 环形数组队列
 **/
public class CircleArrayQueue {
    private int maxSize;
    private int top = 0;
    private int bottom = 0;
    private int[] array;

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        array = new int[maxSize];
    }

    /**
     * 队列是否为空
     **/
    public boolean isEmpty() {
        return top == bottom;
    }

    /**
     * 队列是否已满
     **/
    public boolean isFull() {
        return (bottom + 1) % maxSize == top;
    }

    /**
     * 添加元素
     **/
    public void add(int item) {
        if (isFull())
            throw new CustomException(400, "队列已满");
        array[bottom] = item;
        bottom = (bottom + 1) % maxSize;
    }

    /**
     * 弹出队列第一个元素
     **/
    public int pop() {
        if (isEmpty())
            throw new CustomException(400, "队列为空");
        int temp = array[top];
        top = (top + 1) % maxSize;
        return temp;
    }

    /**
     * 显示队列第一个元素
     **/
    public int peek() {
        if (isEmpty())
            throw new CustomException(400, "队列为空");
        return array[top];
    }

    /**
     * 获取队列实际容量
     **/
    public int size() {
        return (bottom + maxSize - top) % maxSize;
    }

    /**
     * 显示队列详情
     **/
    public void showAll() {
        if (isEmpty())
            throw new CustomException(400, "队列为空");
        for (int i = top; i < top + size(); i++) {
            System.out.printf("array[%d]=%d\t", i % maxSize, array[i % maxSize]);
            if (i == top + size() - 1)
                System.out.println();
        }
    }
}
